package utils;

import com.csvreader.CsvReader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author waxijiang
 */
public class UserUtils {

    public static boolean login(String username, String password, String userFileLocation) {
        if (password.equals(getPasswordByUsername(username, userFileLocation))){
            return true;
        }else {
            return false;
        }
    }

    public static Map<String, String> readAll(String filePath) {
        Map<String, String> users = new HashMap<String, String>();

        try {
            // 创建CSV读对象
            CsvReader csvReader = new CsvReader(filePath);

            // 读表头
            csvReader.readHeaders();
            while (csvReader.readRecord()) {
                users.put(csvReader.get("username"), csvReader.get("password"));
            }
            return users;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过用户名找密码
     * @param username 用户名
     * @return 密码
     */
    public static String getPasswordByUsername(String username, String userFileLocation) {
        Map<String, String> stringStringMap = readAll(userFileLocation);
        for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
            if (entry.getKey().equals(username)) {
                return entry.getValue();
            }
        }
        return null;
    }
}
